package com.test.course.array;

/**
 * @author sujiafa
 * @date 2025/7/7
 */
public class 归并排序 {

    public static void mergeSort(int[] arr) {
        if (arr == null || arr.length <= 1) {
            return;
        }
        // 临时数组用于合并操作
        int[] temp = new int[arr.length];
        mergeSort(arr, 0, arr.length - 1, temp);
    }

    public static void mergeSort(int[] arr, int left, int right, int[] temp) {
        if (left < right) {
            // 当数组大小大于1时继续分割
            int middle = (left + right) / 2;
            mergeSort(arr, left, middle, temp);
            mergeSort(arr, middle + 1, right, temp);
            merge(arr, left, middle, right, temp);
        }
    }

    public static void merge(int[] arr, int left, int middle, int right, int[] temp) {

        // 进行合并操作
        int i = left;
        int j = middle + 1;
        int tempIndex = left;
        while (i <= middle && j <= right) {
            // 比较两边数组，将较小的元素放在前面
            if (arr[i] <= arr[j]) {
                temp[tempIndex++] = arr[i++];
            } else {
                temp[tempIndex++] = arr[j++];
            }
        }

        // 将剩余的元素放入数组
        while (i <= middle) {
            temp[tempIndex++] = arr[i++];
        }
        while (j <= right) {
            temp[tempIndex++] = arr[j++];
        }

        // 将临时数组里的元素填回原来的数组
        for (int k = left; k <= right; k++) {
            arr[k] = temp[k];
        }
    }

    public static void main(String[] args) {
        // 测试用例1：随机顺序
        int[] arr1 = {64, 34, 25, 12, 22, 11, 90};
        System.out.println("排序前的数组：");
        printArray(arr1);
        mergeSort(arr1);
        System.out.println("排序后的数组：");
        printArray(arr1);
    }

    public static void printArray(int[] arr) {
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}
